/*
 * Copyright (c) 2010, 2012 Luan Nguyen Thanh. All rights reserved.
 * 
 * This code is written by Luan Nguyen Thanh, with any partners involved.
 * The use of this code should not be permitted!
 * If you want to use, please do contact me!
 */
package MyIM.client.view.form;

import MyIM.client.engine.Engine;
import MyIM.client.view.component.JTKButton;
import MyIM.client.view.lnf.MetroStyle;
import MyIM.client.view.lnf.SegoeFont;
import MyIM.component.Friend;
import MyIM.utilities.Util;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Image;
import java.awt.event.*;
import java.awt.image.BufferedImage;
import java.util.ArrayList;
import java.util.Date;
import java.util.Observable;
import java.util.Observer;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.*;
import javax.swing.text.BadLocationException;
import javax.swing.text.Style;
import javax.swing.text.StyleConstants;
import javax.swing.text.StyledDocument;
import org.jdesktop.swingx.JXTextArea;

/**
 *
 * @author Luan Nguyen Thanh <tklarryonline@gmail.com>
 */
public class Dialog_Conference extends JFrame implements ActionListener,
        KeyListener, Observer {

    private static int count = 1;
    private ArrayList<Friend> attendees;
    private String currentUserDisplayName;
    private ImageIcon currentUserAvatar;
    //
    private JTextPane chatDisplay;
    private JTextArea chatInput, attendeesDisplay;
    private JButton btnSendMsg, btnInvite;
    private JLabel lblTextCount;
    private Engine engine;
    private int ownerid;
    private String conferenceName;

    public Dialog_Conference(Engine engine, int ownerID) {
        attendees = new ArrayList<>();
        
        this.engine = engine;
        this.ownerid = ownerID;
        this.conferenceName = new String("Conference " + count++);
        this.currentUserAvatar = new ImageIcon(engine.getClient().getAvatar().
                getImage().
                getScaledInstance(72, 72, Image.SCALE_SMOOTH));
        attendees.add(engine.getFriend(engine.getClient().getUID()));
        init();
        initListener();
    }

    public Dialog_Conference(Engine engine, int ownerID, String conferenceName, ArrayList<Friend> attendees) {
        this.attendees = attendees;
        this.engine = engine;
        this.ownerid = ownerID;
        this.conferenceName = conferenceName;
        this.currentUserAvatar = new ImageIcon(engine.getClient().getAvatar().
                getImage().
                getScaledInstance(72, 72, Image.SCALE_SMOOTH));

        init();
        initListener();
    }

    public ArrayList<Friend> getAttendees() {
        return attendees;
    }

    public String getConferenceName() {
        return conferenceName;
    }

    public int getOwnerid() {
        return ownerid;
    }

    
    
    public void addAttendees(Friend friend) {
    }

    private void init() {
        // Initializes the frame
        setTitle(conferenceName);
        setVisible(true);
        setIconImage(Util.makeIcon("Logo").getImage());
        
        chatInput = new JXTextArea("Type here to start chatting");
        chatInput.setColumns(23);
        chatInput.setLineWrap(true);
        chatInput.setRows(4);
        chatInput.setWrapStyleWord(true);

        attendeesDisplay = new JTextArea();
        attendeesDisplay.setColumns(15);
        attendeesDisplay.setLineWrap(true);
        attendeesDisplay.setWrapStyleWord(true);
        attendeesDisplay.setEditable(false);
        attendeesDisplay.setRows(20);
        attendeesDisplay.setBorder(BorderFactory.createEmptyBorder());

        lblTextCount = new JLabel("0/500");
        lblTextCount.setFont(SegoeFont.getSegoeUIFont("normal",
                12f));

        chatDisplay = new JTextPane();
        chatDisplay.setEditable(false);

        btnSendMsg = new JButton("Send");
        btnSendMsg.setActionCommand("send");
        btnSendMsg.setPressedIcon(new ImageIcon(new BufferedImage(1,
                1, BufferedImage.TYPE_INT_ARGB_PRE)));
        btnSendMsg.setVerticalTextPosition(JButton.CENTER);
        btnSendMsg.setHorizontalTextPosition(JButton.CENTER);
        btnSendMsg.setFont(MetroStyle.SMALL_BUTTON_FONT);
        getRootPane().setDefaultButton(btnSendMsg);

        btnInvite = new JTKButton("Invite");
        btnInvite.setActionCommand("invite");
        btnInvite.setPressedIcon(new ImageIcon(new BufferedImage(1,
                1, BufferedImage.TYPE_INT_ARGB_PRE)));
        btnInvite.setVerticalTextPosition(JButton.CENTER);
        btnInvite.setHorizontalTextPosition(JButton.CENTER);
        btnInvite.setFont(MetroStyle.SMALL_BUTTON_FONT);
        
        initLayout();

        setResizable(true);
        pack();
        setLocationRelativeTo(null);
    }

    private void initLayout() {
        setLayout(new BorderLayout(5, 5));
        
        JLabel label = new JLabel("Conference");
        label.setFont(MetroStyle.FORM_TITLE);
        label.setForeground(MetroStyle.LIGHTER_MARINE);
        label.setBorder(BorderFactory.createEmptyBorder(5, 10, 10,
                10));
        add(label, BorderLayout.NORTH);
        
        add(makeChatDisplayPn());

        add(makeAttendeesDisplayPn(), BorderLayout.EAST);

        add(makeChatInputPn(), BorderLayout.SOUTH);
    }

    private JPanel makeChatDisplayPn() {
        JPanel mainPn = new JPanel(new BorderLayout());

        JScrollPane scrollPane = new JScrollPane(chatDisplay);
        mainPn.add(scrollPane);
        
        mainPn.setPreferredSize(new Dimension(450, 400));
        mainPn.setBorder(BorderFactory.createEmptyBorder(0, 10, 0,
                5));

        return mainPn;
    }

    private JPanel makeAttendeesDisplayPn() {
        JPanel mainPn = new JPanel(new BorderLayout());

        JScrollPane scrollPane = new JScrollPane(attendeesDisplay);
        mainPn.add(scrollPane);

        mainPn.add(btnInvite, BorderLayout.NORTH);
        mainPn.setBorder(BorderFactory.createEmptyBorder(0, 5, 0,
                10));

        return mainPn;
    }

    private JPanel makeChatInputPn() {
        JPanel mainPn = new JPanel(new BorderLayout(5, 5));

        JScrollPane scrollPane = new JScrollPane(chatInput);
        mainPn.add(scrollPane);

        JPanel currentUserPn = new JPanel(new BorderLayout(5, 5));
        JLabel label = new JLabel(currentUserAvatar);
        label.setBorder(BorderFactory.createEmptyBorder());
        currentUserPn.add(new JLabel(currentUserAvatar));

        currentUserPn.add(btnSendMsg, BorderLayout.SOUTH);

        mainPn.add(currentUserPn, BorderLayout.EAST);

        mainPn.add(lblTextCount, BorderLayout.NORTH);

        mainPn.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));

        return mainPn;
    }

    public void insertMessage(String displayName, String message) {
        try {
            StyledDocument docStyle = (StyledDocument) chatDisplay.getDocument();

            Style style = docStyle.addStyle("ChatStyle", null);
            StyleConstants.setBold(style, true);
            String chat = displayName + " [" + new Date().toString() + "]:\n";
            docStyle.insertString(docStyle.getLength(), chat, style);
            StyleConstants.setBold(style, false);
            docStyle.insertString(docStyle.getLength(), message+"\n", style);
            chatDisplay.setCaretPosition(docStyle.getLength());
        } catch (BadLocationException ex) {
            Logger.getLogger(Dialog_Chat.class.getName()).log(Level.SEVERE, null,
                    ex);
        }
    }

    private void initListener() {
        chatInput.addKeyListener(this);
        btnSendMsg.addActionListener(this);
        btnInvite.addActionListener(this);
        this.addWindowListener(new WindowAdapter() {

            @Override
            public void windowClosing(WindowEvent e) {
                int option = JOptionPane.showConfirmDialog(Dialog_Conference.this,"Do you want to exit this conference?");
                if (option == JOptionPane.YES_OPTION) {
                    
                    engine.exitConference(ownerid, conferenceName,engine.getClient().getUID(), attendees);
                }
                
                Dialog_Conference.this.setDefaultCloseOperation(
                        JDialog.DISPOSE_ON_CLOSE);
            }
        });
    }

    public void setAttendees(ArrayList<Friend> attendees) {
        this.attendees = attendees;
    }
    
    
    /**
     * *************************************************************************
     * Controller part
     * *************************************************************************
     */
    @Override
    public void keyTyped(KeyEvent e) {
    }

    @Override
    public void keyPressed(KeyEvent e) {
        if (e.getKeyCode() == KeyEvent.VK_ENTER) {
            // 'Enter' to send and 'Shift + Enter' to start new line
            if (e.isShiftDown()) {
                // 'Shift + Enter' event
                addNewLine();
            } else {
                btnSendMsg.doClick();
            }
        }
    }

    @Override
    public void keyReleased(KeyEvent e) {
        checkChatInputLength();
    }

    private void checkChatInputLength() {
        int length = chatInput.getText().length();
        lblTextCount.setText(length + "/500");

        if (length > 500) {
            String chatString = chatInput.getText().substring(0, 500);
            chatInput.setText(chatString);
        }
    }

    private void addNewLine() {
        chatInput.append("\n");
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        String cmd = e.getActionCommand();

        if (cmd.equalsIgnoreCase("send")) {
            engine.sendMessageConference(ownerid, conferenceName, engine.getClient().getUID(),chatInput.getText(), attendees);
            chatInput.setText("");
        }else if(cmd.equalsIgnoreCase("invite")){
            System.out.println("Invite Friend");
            new Dialog_InviteConference(engine, this);
        }
    }
    public void initAttendees(){
        attendeesDisplay.setText("");
        for (Friend friend : attendees) {
            attendeesDisplay.append(friend.getDisplayName()+"\n");
        }
    }
    @Override
    public void update(Observable o, Object arg) {
        String[] args = ((String) arg).split(":");
        insertMessage(args[0], args[1]);
    }
}
